package com.supermarket.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.supermarket.entity.Repair;
import com.supermarket.service.RepairService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("repair")// 一级访问路径
public class RepairController {

    @Autowired//自动装配
    private RepairService repairService;

    @RequestMapping("findAll")
    public Map findAll() {
        List<Repair> repairList = repairService.findAll();

        HashMap<String, Object> map = new HashMap<>();
        map.put("code", 0);
        map.put("msg", "success");
        map.put("count", 1000);
        map.put("data", repairList);

        System.out.println(map);

        return map;
    }

    @RequestMapping("findByPage")
    public Map findByPage(
            @RequestParam(value = "page", required = false, defaultValue = "1") Integer pageNum,
            @RequestParam(value = "limit", required = false, defaultValue = "3") Integer pageSize
    ) {

        //System.out.println(pageNum);//当前页码
        //System.out.println(pageSize);//每页显示条数

        //设置分页参数
        PageHelper.startPage(pageNum, pageSize);
        //紧跟PageHelper.startPage()后的第一个查询方法才会被分页
        List<Repair> repairList = repairService.findAll();

        //封装对象
        PageInfo<Repair> pageInfo = new PageInfo<>(repairList);

        HashMap<String, Object> map = new HashMap<>();
        map.put("code", 0);
        map.put("msg", "success");
        map.put("count", pageInfo.getTotal());//总记录数
        map.put("data", pageInfo.getList());//分页数据

        System.out.println(map);

        return map;
    }

    @RequestMapping("add")
    public void add(Repair repair, HttpServletResponse response, HttpServletRequest request) throws IOException {
        //System.out.println(patient);

        repairService.add(repair);

        //跳转到主页
        response.sendRedirect(request.getContextPath() + "/home.html");
    }

    @RequestMapping("deleteById")
    public String deleteById(String repairID) {

//        System.out.println("============"+id);
        repairService.deleteById(repairID);

        return "success";
    }

    @RequestMapping("updateRepair")
    public String updateRepair(Repair repair) {

        //System.out.println(patient);
        repairService.updateRepair(repair);

        return "success";
    }
}
